<template>
  <!-- <modal :visible="true" @close="close"> -->
  <div class="content sync-container">
    <div class="box">
      <div v-if="electron">
        <progress-bar type="primary" :value="percentage" :max="100"></progress-bar>
        <div class="process-info">{{completeLength}}/{{allLength}}</div>
        <div>
          <p>
            保存目录: <small>{{localPath?localPath:'未选择'}}</small>
            <a :disabled="syncing" @click="selectPath" class="select-path button is-small">选择目录</a>
          </p>
        </div>
        <div>
          <p>
            进度:{{info}}
            <div v-for="f in workersInfo">
              {{f.desc}}
            </div>
          </p>
          <p>
            <a v-if="!syncing" @click="sync" class="button is-success" :disabled="localPath===null">开始同步</a>
            <a v-else class="syncing button is-success">正在同步</a>
          </p>
        </div>
      </div>
      <div v-else class="center">
        <p class="info">不支持浏览器同步</p>
        <p>下载 <a title="快雨点客户端">快雨点客户端</a> 进行同步</p>
      </div>
    </div>
  </div>
  <!-- </modal> -->
</template>
<script>
import {
  isInElectron
} from 'libs/utils'
import {
  Modal
} from 'vue-bulma-modal'
import Loading from 'components/Loading'
import ProgressBar from 'vue-bulma-progress-bar'
const QueueWorker = require('promise-queue-plus')
export default {
  components: {
    Modal,
    Loading,
    ProgressBar
  },
  props: {
    visible: Boolean
  },
  data: function () {
    return {
      workersInfo: [],
      syncing: false,
      electron: isInElectron() ? require('electron') : null,
      info: '尚未开始',
      localPath: null,
      processFile: '',
      loading: true,
      files: [],
      completeLength: 0
    }
  },
  created: function () {
    this.$http.get('//cdn.kuaiyudian.com/k-line/daily/index.txt').then((res) => {
      return res.text()
    }).then((txt) => {
      return txt.split('\n').filter((s) => s.trim() !== '').map((line) => {
        let arr = line.split(',')
        return {
          qfq: arr[0].indexOf('fq') > -1 ? '前复权' : '不复权',
          date: arr[0].substring(0, 10),
          path: arr[0],
          size: parseInt(arr[1]),
          hash: arr[2]
        }
      })
    }).then((files) => {
      this.loading = false
      this.files = files
    })
  },
  computed: {
    allLength: function () {
      return this.files.length
    },
    percentage: function () {
      return this.allLength === 0 ? 0 : parseInt(parseFloat(this.completeLength) / this.allLength * 100)
    }
  },
  watch: {
    percentage: function (n) {
      if (n - this.percentage > 0.01) {
        this.$emit('process', n)
      }
    }
  },
  methods: {
    sync: function () {
      if (this.syncing || this.localPath == null) {
        return
      }
      this.syncing = true
      this.info = '正在同步'
      this.completeLength = 0
      let fs = require('fs')
      let path = require('path')
      let request = require('http')
      let download = (file) => {
        return new Promise((resolve, reject) => {
          let url = `http://cdn.kuaiyudian.com/k-line/daily/${file.path}`
          let localFile = this.localPath + file.path
          let localkDir = localFile.replace(/\/[^\\/]+?$/, '')
          let info = {
            desc: `下载  ${file.path} `,
            path: file.path
          }
          this.workersInfo.push(info)
          if (fs.existsSync(localFile)) {
            info.desc += '已存在,校验'
            let stat = fs.lstatSync(localFile)
            if (stat.size === file.size) {
              return setTimeout(() => {
                resolve()
                this.completeLength += 1
                for (let i in this.workersInfo) {
                  if (this.workersInfo[i].path === file.path) {
                    this.workersInfo.splice(i, 1)
                  }
                }
              }, 0)
            }
          }
          localkDir.split('/').forEach((dir, index, splits) => {
            const parent = splits.slice(0, index).join('/')
            const dirPath = path.resolve(parent, dir)
            if (!fs.existsSync(dirPath)) {
              fs.mkdirSync(dirPath)
            }
          })
          request.get(url, (res) => {
            let stream = fs.createWriteStream(localFile)
            res.pipe(stream).on('finish', () => {
              this.completeLength += 1
              this.$nextTick(function () {
                for (let i in this.workersInfo) {
                  if (this.workersInfo[i].path === file.path) {
                    this.workersInfo.splice(i, 1)
                  }
                }
              })
              resolve()
            })
          }).on('error', (e) => {
            reject()
            for (let i in this.workersInfo) {
              if (this.workersInfo[i].path === file.path) {
                this.workersInfo.desc += e
              }
            }
          })
        })
      }
      let workers = new QueueWorker(1, {
        'retry': 3,
        event_queue_end: () => {
          this.syncing = false
          this.info = '同步完成'
        }
      })
      workers.addLikeArray(this.files, download)
      workers.start()
    },

    selectPath: function () {
      this.electron.remote.dialog.showOpenDialog({
        properties: ['openDirectory']
      }, (path) => {
        if (path) {
          this.localPath = path[0] + '/'
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.sync-container {
  .box {
    position: relative;
  }
  .select-path {
    margin-left: 10px;
  }
  .button.syncing {
    padding-left: 20px;
    pointer-events: none;
    opacity: 0.8;
  }
  .button.syncing:after {
    animation: spinAround 500ms infinite linear;
    border: 2px solid #dbdbdb;
    border-radius: 290486px;
    border-right-color: transparent;
    border-top-color: transparent;
    content: "";
    display: block;
    height: 16px;
    position: relative;
    width: 16px;
    margin-top: -8px;
    left: 5%;
    top: 50%;
    position: absolute;
    position: absolute !important;
  }
  .center {
    text-align: center
  }
  .process-info {
    width: 100px;
    margin: 0 auto;
  }
  ul {
    list-style: none;
  }
}
</style>
